package cn.code.pojo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class ResponseParser {

    private static final Pattern REF_PATTERN =
            Pattern.compile("\\^\\$(\\d+)\\$\\^");

    public static List<ModelReference> extractReferences(String response) {
        List<ModelReference> references = new ArrayList<>();

        // 1. 匹配所有引用标记
        Matcher matcher = REF_PATTERN.matcher(response);
        while (matcher.find()) {
            ModelReference ref = new ModelReference();
            ref.setIndex(Integer.parseInt(matcher.group(1)));
            references.add(ref);
        }

        // 2. 解析关联的JSON数据
        references.forEach(ref -> {
            String jsonPattern = String.format(
                    "\\^\\$%d\\$\\^ \\{([^}]+)\\}",
                    ref.getIndex()
            );
            Pattern p = Pattern.compile(jsonPattern);
            Matcher m = p.matcher(response);

            if (m.find()) {
                String json = "{" + m.group(1) + "}";
                try {
                    JsonNode node = new ObjectMapper().readTree(json);
                    ref.setTitle(node.path("标题").asText());
                    ref.setUrl(node.path("来源").asText());
                    ref.setContent(node.path("内容").asText());
                } catch (JsonProcessingException e) {
                    log.error("JSON解析失败", e);
                }
            }
        });

        return references;
    }
}
